package com.ruoyi.web.controller.module.product;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.MathUtil;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.excel.ProductOrderExcel;
import com.ruoyi.system.domain.module.excel.ProductOrderMerDetailExcel;
import com.ruoyi.system.domain.module.excel.ProductOrderMerTotalExcel;
import com.ruoyi.system.domain.module.mer.Mer;
import com.ruoyi.system.domain.module.product.*;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.property.PropertyFeeOrder;
import com.ruoyi.system.domain.module.wx.UserIntegralRecord;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.mer.IMerService;
import com.ruoyi.system.service.module.product.*;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.web.controller.common.BaseController;
import com.vdurmont.emoji.EmojiParser;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Validated
@Api(value = "订单控制器", tags = {"订单管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/order")
public class ProductOrderController extends BaseController {

    private final IProductOrderService productOrderService;
    private final IProductOrderInfoService productOrderInfoService;
	private final IMerService merService;
    private final IPropertyService propertyService;
    private final IEstateService estateService;
	private final IWxUserService wxUserService;
	private final IProductService productService;
	private final IProductAttrValueService productAttrValueService;
    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @PreAuthorize("@ss.hasPermi('module:productorder:list')")
    @GetMapping("/list")
    public TableDataInfo<ProductOrder> list(@Validated ProductOrder productOrder) {
        SysUser sysUser = getUser();
        QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        } else if(sysUser.getUserType() == 4){//商家
            qw.eq("mer_id",sysUser.getMerId());
        }else{
            if(productOrder.getPropertyId()!=null){
                qw.eq("property_id",productOrder.getPropertyId());
            }
            if(productOrder.getEstateId()!=null){
                qw.eq("estate_id",productOrder.getEstateId());
            }
            if(productOrder.getMerId()!=null){
                qw.eq("mer_id",productOrder.getMerId());
            }
        }
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            qw.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
        }

		if(productOrder.getPlatform()!=null){
			qw.eq("platform",productOrder.getPlatform());
		}

		if(productOrder.getPayType()!=null){
			qw.eq("pay_type",productOrder.getPayType());
		}


		if(productOrder.getSettlementState() != null){
			qw.eq("settlement_state",productOrder.getSettlementState());
		}

        if(productOrder.getStatus()!=null){
        	if(productOrder.getStatus() == 2){
        		//订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
				Integer[] states = new Integer[]{ 2, 3, 4 };
				qw.in("status",states);
			} else if(productOrder.getStatus() == 0){
				Integer[] states = new Integer[]{ 0,1 };
				qw.in("status",states);
			} else if(productOrder.getStatus() == 10){
				qw.eq("status",2);
			}else{
				qw.eq("status",productOrder.getStatus());
			}
		}
//		Integer[] states = new Integer[]{ 2, 3, 4 };
//		qw.in("status",states);

        if(StrUtil.isNotEmpty(productOrder.getOrderNo())){
            qw.like("order_no",productOrder.getOrderNo());
        }
		qw.eq("is_del", 0);
        qw.orderByDesc("create_time");
		TableDataInfo<ProductOrder> td = PageUtils.buildDataInfo(productOrderService.page(PageUtils.buildPage(),qw));
        List<ProductOrder> list = td.getRows();
        list.forEach(order->{
			Mer mer = merService.getById(order.getMerId());
			if(mer != null){
				order.setShopName(mer.getShopName());
			}

            Estate estate = estateService.findById(order.getEstateId());
            if(estate!=null){
                order.setEstateName(estate.getEstateName());
            }
            if(StrUtil.isNotEmpty(order.getRealName())){
				order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
			}

            WxUser wxUser = wxUserService.findById(order.getUserId());
			if(wxUser!=null){
				if(StrUtil.isNotEmpty(wxUser.getNickName())){
					order.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
				}
			}

            Property property = propertyService.findById(order.getPropertyId());
            if(property!=null){
                order.setPropertyName(property.getPropertyName());
            }

			if(productOrder.getIsShowInfo() != null && productOrder.getIsShowInfo() == 1){
				order.setIsCheck(true);
				QueryWrapper<ProductOrderInfo> qwInfo = new QueryWrapper<>();
				qwInfo.eq("order_id",order.getId());
				List<ProductOrderInfo> listInfo = productOrderInfoService.list(qwInfo);
				if(CollUtil.isNotEmpty(listInfo)){
					for (ProductOrderInfo orderInfo : listInfo){
						if(StrUtil.isEmpty(orderInfo.getSkuName())){
							ProductAttrValue productAttrValue = productAttrValueService.findById(orderInfo.getSkuId());
							if(productAttrValue!=null){
								orderInfo.setSkuName(productAttrValue.getSku());
							}
						}
						Product product = productService.findById(orderInfo.getProductId());
						if(product!=null){
							orderInfo.setProductName(product.getStoreName());
						}
					}
				}
				order.setOrderInfos(listInfo);

			}
		});

		Map<String,Object> map = new HashMap<>();

		map.put("discountRate", 0);
		if(productOrder.getMerId()!=null){
			Mer mer = merService.getById(productOrder.getMerId());
			if(mer!= null){
				map.put("discountRate", mer.getDiscountRate());
			}
		}
		td.setOtherData(map);

        return td;
    }


	/**
	 * 查询订单列表
	 */
	@ApiOperation("查询积分订单列表")
	@PreAuthorize("@ss.hasPermi('module:productorder:list')")
	@GetMapping("/pointsOrderlist")
	public TableDataInfo<ProductOrder> pointsOrderlist(@Validated ProductOrder productOrder) {
		SysUser sysUser = getUser();
		QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){//小区
			qw.eq("estate_id",sysUser.getEstateId());
		} else if(sysUser.getUserType() == 4){//商家
			qw.eq("mer_id",sysUser.getMerId());
		}else{
			if(productOrder.getPropertyId()!=null){
				qw.eq("property_id",productOrder.getPropertyId());
			}
			if(productOrder.getEstateId()!=null){
				qw.eq("estate_id",productOrder.getEstateId());
			}
			if(productOrder.getMerId()!=null){
				qw.eq("mer_id",productOrder.getMerId());
			}
		}
		if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
			qw.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
		}

		if(productOrder.getPlatform()!=null){
			qw.eq("platform",productOrder.getPlatform());
		}

		if(productOrder.getPayType()!=null){
			qw.eq("pay_type",productOrder.getPayType());
		}


		if(productOrder.getSettlementState() != null){
			qw.eq("settlement_state",productOrder.getSettlementState());
		}

		if(productOrder.getStatus()!=null){
			if(productOrder.getStatus() == 2){
				//订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
				Integer[] states = new Integer[]{ 2, 3, 4 };
				qw.in("status",states);
			} else if(productOrder.getStatus() == 0){
				Integer[] states = new Integer[]{ 0,1 };
				qw.in("status",states);
			}else{
				qw.eq("status",productOrder.getStatus());
			}
		}
//		Integer[] states = new Integer[]{ 2, 3, 4 };
//		qw.in("status",states);

		if(StrUtil.isNotEmpty(productOrder.getOrderNo())){
			qw.like("order_no",productOrder.getOrderNo());
		}
		qw.eq("is_del", 0);
		qw.eq("is_can_use_golden", 1);
		qw.orderByDesc("create_time");
		TableDataInfo<ProductOrder> td = PageUtils.buildDataInfo(productOrderService.page(PageUtils.buildPage(),qw));
		List<ProductOrder> list = td.getRows();
		list.forEach(order->{
			Mer mer = merService.getById(order.getMerId());
			if(mer != null){
				order.setShopName(mer.getShopName());
			}

			Estate estate = estateService.findById(order.getEstateId());
			if(estate!=null){
				order.setEstateName(estate.getEstateName());
			}
			if(StrUtil.isNotEmpty(order.getRealName())){
				order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
			}

			WxUser wxUser = wxUserService.findById(order.getUserId());
			if(wxUser!=null){
				if(StrUtil.isNotEmpty(wxUser.getNickName())){
					order.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
				}
			}

			Property property = propertyService.findById(order.getPropertyId());
			if(property!=null){
				order.setPropertyName(property.getPropertyName());
			}

			if(productOrder.getIsShowInfo() != null && productOrder.getIsShowInfo() == 1){
				order.setIsCheck(true);
				QueryWrapper<ProductOrderInfo> qwInfo = new QueryWrapper<>();
				qwInfo.eq("order_id",order.getId());
				List<ProductOrderInfo> listInfo = productOrderInfoService.list(qwInfo);
				if(CollUtil.isNotEmpty(listInfo)){
					for (ProductOrderInfo orderInfo : listInfo){
						if(StrUtil.isEmpty(orderInfo.getSkuName())){
							ProductAttrValue productAttrValue = productAttrValueService.findById(orderInfo.getSkuId());
							if(productAttrValue!=null){
								orderInfo.setSkuName(productAttrValue.getSku());
							}
						}
						Product product = productService.findById(orderInfo.getProductId());
						if(product!=null){
							orderInfo.setProductName(product.getStoreName());
						}
					}
				}
				order.setOrderInfos(listInfo);

			}
		});

		Map<String,Object> map = new HashMap<>();

		map.put("discountRate", 0);
		if(productOrder.getMerId()!=null){
			Mer mer = merService.getById(productOrder.getMerId());
			if(mer!= null){
				map.put("discountRate", mer.getDiscountRate());
			}
		}
		td.setOtherData(map);

		return td;
	}


    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @GetMapping("/statistics/list")
    public TableDataInfo<ProductOrderExcel> statisticsList(@Validated ProductOrder productOrder) {
        Map<String,Object> map = new HashMap<>();
        SysUser sysUser = getUser();
        if(sysUser.getUserType() == 2){//物业公司
            map.put("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            map.put("estate_id",sysUser.getEstateId());
        }
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
            map.put("end_time",productOrder.getBeginDate() + " 23:59:59");
        }
        TableDataInfo<ProductOrderExcel> td = PageUtils.buildDataInfo(productOrderService.selectPageExcelListByTime(PageUtils.buildPage(),map));
        return td;
    }

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @GetMapping("/mer/list")
    public TableDataInfo<ProductOrder> merList(@Validated ProductOrder productOrder) {
        Map<String,Object> map = new HashMap<>();
        SysUser sysUser = getUser();
        if(sysUser.getUserType() == 2){//物业公司
            map.put("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            map.put("estate_id",sysUser.getEstateId());
        } else if(sysUser.getUserType() == 4){//商家
            map.put("mer_id",sysUser.getMerId());
        }
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
            map.put("end_time",productOrder.getBeginDate() + " 23:59:59");
        }


		map.put("order_type", productOrder.getOrderType());

        if(StrUtil.isNotEmpty(productOrder.getOrderNo())){
            map.put("order_no", productOrder.getOrderNo());
        }
		if(productOrder.getStatus()!=null){
			map.put("status",productOrder.getStatus());
		}

		if(productOrder.getIsVerify()!=null){
            map.put("is_verify",productOrder.getIsVerify());
        }

        TableDataInfo<ProductOrder> td = PageUtils.buildDataInfo(productOrderInfoService.selectOrderListByMer(PageUtils.buildPage(),map));
        List<ProductOrder> list = td.getRows();
        list.forEach(order->{
            Mer mer = merService.getById(order.getMerId());
            if(mer != null){
                order.setShopName(mer.getShopName());
            }

            Estate estate = estateService.findById(order.getEstateId());
            if(estate!=null){
                order.setEstateName(estate.getEstateName());
            }

            Property property = propertyService.findById(order.getPropertyId());
            if(property!=null){
                order.setPropertyName(property.getPropertyName());
            }
        });
        return td;
    }
    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @GetMapping("/listByFenrun")
    public TableDataInfo<ProductOrder> listByFenrun(@Validated ProductOrder productOrder) {
        SysUser sysUser = getUser();
        QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
        if(sysUser!=null){
            if(sysUser.getUserType() == 2){//物业公司
                qw.eq("property_id",sysUser.getPropertyId());
            } else if(sysUser.getUserType() == 3){//小区
                qw.eq("estate_id",sysUser.getEstateId());
            } else if(sysUser.getUserType() == 4) {//商家
            	if(productOrder.getMerId()!=null){
					qw.eq("mer_id",productOrder.getMerId());
				}else{

					List<Integer> merIds = new ArrayList<>();
					Map<String,Object> map = new HashMap<>();
					map.put("sys_user_id",sysUser.getUserId());
					List<Mer> list = merService.selectMerListByUserId(map);
					if(CollUtil.isNotEmpty(list)){
						for (Mer mer : list){
							merIds.add(mer.getId());
						}
					}
					if(merIds.size() > 0){
						qw.in("mer_id",merIds);
					}else{
						qw.in("mer_id",sysUser.getMerId());
					}
				}
            }
        }
        qw.in("status",new Integer[]{ 2, 3, 4 });
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            qw.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
        }

        qw.orderByDesc("create_time");
        TableDataInfo<ProductOrder> td = PageUtils.buildDataInfo(productOrderService.page(PageUtils.buildPage(),qw));
        List<ProductOrder> list = td.getRows();
        list.forEach(order -> {
            Mer mer = merService.getById(order.getMerId());
            if(mer!=null){
                order.setShopName(mer.getShopName());
            }
            if(StrUtil.isNotEmpty(order.getRealName())){
				order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
			}

        });
        Map<String,Object> map = new HashMap<>();
        map.put("userType",sysUser.getUserType());


        //今日交易额
        Map<String,Object> mapOrder = new HashMap<>();
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())) {
            mapOrder.put("begin_time", productOrder.getBeginDate() + " 00:00:00");
            mapOrder.put("end_time", productOrder.getEndDate() + " 23:59:59");
        }

        if(sysUser!=null){
            if(sysUser.getUserType() == 2){//物业公司

            	//总交易金额
                mapOrder.put("property_id",sysUser.getPropertyId());
                double orderMoneyAll = productOrderService.selectTotalMoneyByTime(mapOrder);
                map.put("orderMoneyAll",orderMoneyAll);

                // 总分润
                double fenRunProperty = productOrderService.selectFenRunProperty(mapOrder);
                map.put("fenRun",fenRunProperty);
            } else if(sysUser.getUserType() == 3){//小区
                mapOrder.put("estate_id",sysUser.getEstateId());

                //总交易金额
                double orderMoneyAll = productOrderService.selectTotalMoneyByTime(mapOrder);
                map.put("orderMoneyAll",orderMoneyAll);

                //总分润
                double fenRunProperty = productOrderService.selectFenRunEstate(mapOrder);
                map.put("fenRun",fenRunProperty);
            }else if(sysUser.getUserType() == 4){//商家
            	if(productOrder.getMerId() !=null){
					mapOrder.put("mer_id",productOrder.getMerId());
				}else{
					mapOrder.put("mer_id",0);
				}
				mapOrder.put("sys_user_id",sysUser.getUserId());
				//总交易金额
				Map<String,Object> orderMoneyAll = productOrderService.selectFenRunMer(mapOrder);
				map.putAll(orderMoneyAll);
            }else {//平台
            	//总交易金额
                double orderMoneyAll = productOrderService.selectTotalMoneyByTime(mapOrder);
                map.put("orderMoneyAll",orderMoneyAll);

                double fenRunPlatform = productOrderService.selectFenRunPlatform(mapOrder);
                map.put("fenRun",fenRunPlatform);
            }
        }
        td.setOtherData(map);
        return td;
    }

    /**
     * 导出订单列表
     */
    @ApiOperation("导出订单列表")
    @PreAuthorize("@ss.hasPermi('module:productorder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<ProductOrder> export(@Validated ProductOrder productOrder) {
        SysUser sysUser = getUser();
        QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        } else if(sysUser.getUserType() == 4){//商家
            qw.eq("mer_id",sysUser.getMerId());
        }else{
            if(productOrder.getPropertyId()!=null){
                qw.eq("property_id",productOrder.getPropertyId());
            }
            if(productOrder.getEstateId()!=null){
                qw.eq("estate_id",productOrder.getEstateId());
            }
            if(productOrder.getMerId()!=null){
                qw.eq("mer_id",productOrder.getMerId());
            }
        }
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            qw.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
        }

        if(productOrder.getPlatform()!=null){
            qw.eq("platform",productOrder.getPlatform());
        }

        if(productOrder.getPayType()!=null){
            qw.eq("pay_type",productOrder.getPayType());
        }

        if(productOrder.getStatus()!=null){
            if(productOrder.getStatus() == 2){
                //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                Integer[] states = new Integer[]{ 2, 3, 4 };
                qw.in("status",states);
            } else if(productOrder.getStatus() == 0){
                Integer[] states = new Integer[]{ 0,1 };
                qw.in("status",states);
            } else if(productOrder.getStatus() == 10){
				qw.eq("status",2);
			}else{
                qw.eq("status",productOrder.getStatus());
            }
        }



		if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
			qw.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
		}

        if(StrUtil.isNotEmpty(productOrder.getOrderNo())){
            qw.like("order_no",productOrder.getOrderNo());
        }
		qw.groupBy("user_id");
        qw.orderByDesc("mer_id,create_time");
        List<ProductOrder> list = productOrderService.list(qw);
//        List<ProductOrder> list = td.getRows();
        for (ProductOrder list1:list){

			Mer mer = merService.getById(list1.getMerId());
			if(mer != null){
				list1.setShopName(mer.getShopName());
			}

            if (list1.getEstateId()!=null){
                Estate estate = estateService.getById(list1.getEstateId());
                if (ObjectUtil.isNotEmpty(estate)){
                    list1.setEstateName(estate.getEstateName());
                }
            }
            if (list1.getPropertyId()!=null){
                Property property = propertyService.getById(list1.getPropertyId());
                if (ObjectUtil.isNotEmpty(property)) {
                    list1.setPropertyName(property.getPropertyName());
                }
            }
            if (list1.getUserId()!=null){
                WxUser user = wxUserService.getById(list1.getUserId());
                if (ObjectUtil.isNotEmpty(user)) {
                    list1.setNickName(user.getNickName());
                }
            }
            if (list1.getCreateTime()!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                list1.setPayTimes(sdf.format(list1.getCreateTime()));
            }
			//查询数量
			QueryWrapper<ProductOrder> qw1 = new QueryWrapper<>();
			if(sysUser.getUserType() == 2){//物业公司
				qw1.eq("property_id",sysUser.getPropertyId());
			} else if(sysUser.getUserType() == 3){//小区
				qw1.eq("estate_id",sysUser.getEstateId());
			} else if(sysUser.getUserType() == 4){//商家
				qw1.eq("mer_id",sysUser.getMerId());
			}else{
				if(productOrder.getPropertyId()!=null){
					qw1.eq("property_id",productOrder.getPropertyId());
				}
				if(productOrder.getEstateId()!=null){
					qw1.eq("estate_id",productOrder.getEstateId());
				}
				if(productOrder.getMerId()!=null){
					qw1.eq("mer_id",productOrder.getMerId());
				}
			}
			if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
				qw1.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
			}

			if(productOrder.getPlatform()!=null){
				qw1.eq("platform",productOrder.getPlatform());
			}

			if(productOrder.getPayType()!=null){
				qw1.eq("pay_type",productOrder.getPayType());
			}

//			states = new Integer[]{ 2, 3, 4 };
//			qw1.in("status",states);
			if(productOrder.getStatus()!=null){
				if(productOrder.getStatus() == 2){
					//订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
					Integer[] states = new Integer[]{ 2, 3, 4 };
					qw1.in("status",states);
				} else if(productOrder.getStatus() == 0){
					Integer[] states = new Integer[]{ 0,1 };
					qw1.in("status",states);
				} else if(productOrder.getStatus() == 10){
					qw1.eq("status",2);
				}else{
					qw1.eq("status",productOrder.getStatus());
				}
			}

			if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
				qw1.between("create_time",productOrder.getBeginDate() + " 00:00:00",productOrder.getEndDate() + " 23:59:59");
			}

			if(StrUtil.isNotEmpty(productOrder.getOrderNo())){
				qw1.like("order_no",productOrder.getOrderNo());
			}
			List<ProductOrder> list2 = productOrderService.list(qw1);
			Integer counts = 0;
			for (ProductOrder list3:list2){
				if (list3.getUserId().equals(list1.getUserId())){
					counts+=1;
				}
			}
			list1.setCounts(counts);
        }
        ExcelUtil<ProductOrder> util = new ExcelUtil<ProductOrder>(ProductOrder.class);
        return util.exportExcel(list, "订单");
    }


    /**
     * 导出用户的积分记录列表
     */
    @ApiOperation("物业总数据导出")
    @PreAuthorize("@ss.hasPermi('module:productorder:export')")
    @Log(title = "物业总数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportTotal")
    public AjaxResult<UserIntegralRecord> exportTotal(@Validated  ProductOrder productOrder) {
        Map<String,Object> map = new HashMap<>();

		if(productOrder.getOrderType()!=null){
			map.put("order_type",productOrder.getOrderType());
		}
        if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
            map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
            map.put("end_time",productOrder.getEndDate() + " 23:59:59");
        }
        List<ProductOrderExcel> list = productOrderService.selectExcelListByTime(map);
        ExcelUtil<ProductOrderExcel> util = new ExcelUtil<>(ProductOrderExcel.class);
        return util.exportExcel(list, "所有消费统计记录");
    }


	/**
	 * 商家总数据导出
	 */
	@ApiOperation("商家总数据导出")
	@PreAuthorize("@ss.hasPermi('module:productorder:export')")
	@Log(title = "商家总数据导出", businessType = BusinessType.EXPORT)
	@GetMapping("/exportMerTotal")
	public AjaxResult<UserIntegralRecord> exportMerTotal(@Validated  ProductOrder productOrder) {
		Map<String,Object> map = new HashMap<>();
        if(productOrder.getMerId()!=null){
            map.put("mer_id",productOrder.getMerId());
        }
		map.put("order_type",0);
		if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
			map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
			map.put("end_time",productOrder.getEndDate() + " 23:59:59");
		}
		List<ProductOrderMerTotalExcel> list = productOrderService.selectExcelMerTotalListByTime(map);
		ExcelUtil<ProductOrderMerTotalExcel> util = new ExcelUtil<>(ProductOrderMerTotalExcel.class);
		return util.exportExcel(list, "商家核销订单统计");
	}


	/**
	 * 商家明细导出
	 */
	@ApiOperation("商家明细导出")
	@PreAuthorize("@ss.hasPermi('module:productorder:export')")
	@Log(title = "商家明细导出", businessType = BusinessType.EXPORT)
	@GetMapping("/exportMerDetail")
	public AjaxResult<UserIntegralRecord> exportMerDetail(@Validated  ProductOrder productOrder) {
		Map<String,Object> map = new HashMap<>();
        if(productOrder.getMerId()!=null){
            map.put("mer_id",productOrder.getMerId());
        }
        map.put("order_type",0);
		if(StrUtil.isNotEmpty(productOrder.getBeginDate())){
			map.put("begin_time",productOrder.getBeginDate() + " 00:00:00");
			map.put("end_time",productOrder.getEndDate() + " 23:59:59");
		}
		List<ProductOrderMerDetailExcel> list = productOrderService.selectExcelMerDetailListByTime(map);
		ExcelUtil<ProductOrderMerDetailExcel> util = new ExcelUtil<>(ProductOrderMerDetailExcel.class);
		return util.exportExcel(list, "所有消费统计记录");
	}

    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@ss.hasPermi('module:productorder:query')")
    @GetMapping("/{id}")
    public AjaxResult<ProductOrder> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
    	ProductOrder order = productOrderService.getById(id);
    	if(order!=null){
			Mer mer = merService.getById(order.getMerId());
			if(mer != null){
				order.setShopName(mer.getShopName());
			}

			Estate estate = estateService.findById(order.getEstateId());
			if(estate!=null){
				order.setEstateName(estate.getEstateName());
			}
			if(StrUtil.isNotEmpty(order.getRealName())){
				order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
			}

			Property property = propertyService.findById(order.getPropertyId());
			if(property!=null){
				order.setPropertyName(property.getPropertyName());
			}
		}
        return AjaxResult.success(order);
    }

    /**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@ss.hasPermi('module:productorder:query')")
    @GetMapping("/mer/{id}")
    public ProductOrder getOrderInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ProductOrder order = productOrderService.getById(id);
        if(order!=null){
            Mer mer = merService.getById(order.getMerId());
            if(mer != null){
                order.setDiscountRate(mer.getDiscountRate());
                double total = order.getTotalPrice().doubleValue();
                double zhekou = order.getDiscountRate().doubleValue();
                System.out.println(total+"======应付");
                System.out.println(zhekou+"======折扣");
                double pay = MathUtil.getDoubleUp(total * zhekou/10);
                double dk = MathUtil.getDoubleUp(total-pay);
                order.setPay(pay);
                String pay1 = String.valueOf(pay);
                String dikou = String.valueOf(dk);
                BigDecimal bigDecimal = new BigDecimal(pay1);
                BigDecimal bigDecimal2 = new BigDecimal(dikou);
                order.setPayPrice(bigDecimal);
                System.out.println(order.getPayPrice()+"======支付");
                order.setDiscountDikouPrice(bigDecimal2);
                boolean ret = productOrderService.updateById(order);
            }
        }
        return order;
    }

	/**
     * 新增订单
     */
    @ApiOperation("新增订单")
    @PreAuthorize("@ss.hasPermi('module:productorder:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody ProductOrder productOrder) {
        return toAjax(productOrderService.save(productOrder) ? 1 : 0);
    }

    /**
     * 修改订单
     */
    @ApiOperation("修改订单")
    @PreAuthorize("@ss.hasPermi('module:productorder:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody ProductOrder productOrder) {
        boolean ret = productOrderService.updateById(productOrder);
        return toAjax(ret);
    }


	@Log(title = "重置二维码")
    @PostMapping("/resetQrCode")
    @ResponseBody
    @PreAuthorize("@ss.hasPermi('module:merTable:edit')")
    public AjaxResult<Void> resetQrCode(@RequestBody ProductOrder productOrder) {
        if(productOrder.getId()!=null){
            try{
                productOrder = productOrderService.getById(productOrder.getId());
                if(productOrder != null){
                    String qrCode = "";
                    String fileName = "";
                    String content = "";
                    fileName = "product_order_" + productOrder.getOrderNo() + ".jpg";
                    content = "https://www.caihengyun.com/wxmini/order/qr?order_id=" + productOrder.getId();

                    int upload_type = FileUploadUtils.TYPE_PRODUCT_ORDER;
                    System.out.println("content:  "+ content);
                    String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, productOrder.getOrderNo(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
                    qrCode = img_key;
                    productOrder.setQrCodeUrl(qrCode);
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (productOrderService.updateById(productOrder)) {
                return AjaxResult.success();
            }
        }
        return AjaxResult.error();
    }


    /**
	 * 修改订单
	 */
	@ApiOperation("修改订单")
	@PreAuthorize("@ss.hasPermi('module:productorder:edit')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping("/refund")
	public AjaxResult<Void> refund(@Validated(EditGroup.class) @RequestBody ProductOrder productOrder) {
		int ret = productOrderService.refundOp(productOrder);
		return toAjax(ret);
	}

    /**
     * 删除订单
     */
    @ApiOperation("删除订单")
    @PreAuthorize("@ss.hasPermi('module:productorder:remove')")
    @Log(title = "订单" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
		for (Long id : ids){
			ProductOrder order = productOrderService.findById(id);
			if(order != null){
				order.setIsDel(1);
				productOrderService.updateById(order);
			}
		}
		return toAjax(1);
    }


    /**
     * 核销订单
     */
    @ApiOperation("核销订单")
    @PreAuthorize("@ss.hasPermi('module:productorder:verify')")
    @Log(title = "订单" , businessType = BusinessType.UPDATE)
    @PostMapping("/verify/{ids}")
    public AjaxResult<Void> verify(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        for (Long id : ids) {
            ProductOrderInfo orderInfo = productOrderInfoService.getById(id);
            if(orderInfo!=null){
                if(orderInfo.getIsVerify() == 0){
                    orderInfo.setIsVerify(1);
                    productOrderInfoService.updateById(orderInfo);
                }
            }
        }
        return toAjax(1);
    }



	/**
	 * 结算订单
	 */
	@ApiOperation("结算订单")
	@PreAuthorize("@ss.hasPermi('module:productorder:settlement')")
	@Log(title = "结算订单" , businessType = BusinessType.UPDATE)
	@PostMapping("/settlement/{ids}")
	public AjaxResult<Void> settlement(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
		for (Long id : ids) {
			ProductOrder order = productOrderService.getById(id);
			if(order!=null){
				if(order.getSettlementState() == 0){
					order.setSettlementState(1);
					order.setSettlementTime(new Date());
					productOrderService.updateById(order);
				}
			}
		}
		return toAjax(1);
	}
}
